package com.yorick.logic.service;

import com.google.protobuf.ByteString;
import com.yorick.logic.entity.Account;
import com.yorick.logic.entity.Audio;
import com.yorick.logic.entity.Location;
import com.yorick.netty.WebSocketServerHandler;
import com.yorick.netty.utils.ServerUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.TimerTask;

@Slf4j
public class SyncAudioScheduler extends TimerTask {

    @Override
    public void run() {
        for (Map.Entry<String, ByteBuf> entry : Account.audios.entrySet()) {
            ByteBuf byteBuf = entry.getValue().readBytes(entry.getValue().readableBytes());
            byte[] body = new byte[byteBuf.readableBytes()];
            entry.getValue().getBytes(0, body);
            com.yorick.logic.protobuf.Audio.S2CAudio s2CAudio = com.yorick.logic.protobuf.Audio.S2CAudio.newBuilder()
                            .setAudio(ByteString.copyFrom(body))
                                    .build();
            System.out.println(body.length);
            entry.getValue().discardReadBytes();
            channelSend(WebSocketServerHandler.channels,4, s2CAudio.toByteArray());
        }
    }

    public void channelSend(ChannelGroup channel, int msg, byte[] body) {
        byte[] s_data = new byte[body.length + 6];
        byte[] s_id = ServerUtil.intToByteArray(msg);
        byte[] s_length = ServerUtil.short2Byte((short) body.length);
        System.arraycopy(s_length, 0, s_data, 0, s_length.length);
        System.arraycopy(s_id, 0, s_data, 2, s_id.length);
        System.arraycopy(body, 0, s_data, 6, body.length);
        ByteBuf resp = Unpooled.copiedBuffer(s_data);
        channel.writeAndFlush(new BinaryWebSocketFrame(resp));
    }
}
